package com.web.controller;

import com.domain.Department;
import com.github.pagehelper.PageInfo;
import com.qo.PageResult;
import com.qo.QueryObject;
import com.service.DepartmentService;
import com.util.JsonResult;
import com.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author shkstart
 * @create 2022/3/11-11:46
 */
@Controller
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private DepartmentService service;

    //查询部门
    @RequiredPermission(name = "部门列表",expression = "department:list")
    @RequestMapping("/list")   //可以访问 8080/department/list.do 默认自动添加.do
    public String list(Model model, QueryObject queryObject){
        //分页查询数据
        PageInfo<Department> result = service.query(queryObject);
        model.addAttribute("result",result);
        // 跳转页面 /WEB-INF/views/department/list.jsp
        return "department/list";
    }

    //删除部门
    @RequiredPermission(name = "部门删除",expression = "department:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null){  //传id值就删除对应的部门数据
                service.delete(id);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    //添加、编辑
    //从前端页面可知，如携带id，则是编辑；若没有id，则是添加
    @RequiredPermission(name = "部门编辑",expression = "department:input")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        if (id != null) {  //是编辑，需要查询被修改的部门，回显在页面上
            model.addAttribute("entity",service.get(id));
        }
        // 跳转页面 /WEB-INF/views/department/input.jsp
        return "department/input";
    }

    //保存部门
    @RequiredPermission(name = "部门保存或更新",expression = "department:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Department department){
        if (department.getId() != null) {  //是编辑
            service.update(department);
        }else{   //是添加
            service.save(department);
        }
        return "redirect:/department/list.do";  //让浏览器重新发一次请求
    }

}
